package com.halachawiki.server.data;

import java.util.ArrayList;
import java.util.List;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Transaction;

public class LatestVersionMap {
	
	public static Key getLatestVersionId(Key entityId, String table) {
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		Entity latestVersionMap;
		try {
			latestVersionMap = datastore.get(entityId);
		} catch (EntityNotFoundException e) {
			return null;
		}
		return (Key) latestVersionMap.getProperty("LatestVersion");
	}
	
	public static void setLatestVersionId(Key entityId, String table, Key versionId)
	{
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		Transaction txn = datastore.beginTransaction();
		try {
			Entity latestVersionMap;
			try {
				latestVersionMap = datastore.get(entityId);
			} catch (EntityNotFoundException e) {
				throw new RuntimeException("Entity not found");
			}
			latestVersionMap.setProperty("LatestVersion", versionId);
			datastore.put(latestVersionMap);

			txn.commit();
		} finally {
			if (txn.isActive()) {
				txn.rollback();
			}
		}
	}
	
	public static Key newEntityId(String table) {
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		Transaction txn = datastore.beginTransaction();
		try {
			Entity latestVersionMap = new Entity("LatestVersionMap");
			latestVersionMap.setProperty("Table", table);
			datastore.put(latestVersionMap);
			txn.commit();
			return latestVersionMap.getKey();
		} finally {
			if (txn.isActive()) {
				txn.rollback();
			}
		}
	}
	
	public static List<Key> getAllLatestVersions(String table) {
		ArrayList<Key> allLatestVersions = new ArrayList<Key>();
		Query q = new Query("LatestVersionMap");
		q.addFilter("Table", Query.FilterOperator.EQUAL, table);
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		PreparedQuery pq = datastore.prepare(q);

		for (Entity result : pq.asIterable()) {
			Key latestVersion = (Key)result.getProperty("LatestVersion");
			if (latestVersion != null)
				allLatestVersions.add(latestVersion);
		}
		return allLatestVersions;
	}
}
